import { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { 
  ChevronLeft,
  Search,
  FileText,
  Video,
  Image,
  Presentation,
  HelpCircle,
  List,
  Cloud,
  MessageSquare,
  BarChart3,
  Users,
  BookOpen,
  Target,
  Type,
  ExternalLink,
  Palette,
  Brain,
  Star,
  Clock
} from 'lucide-react';

interface ModuleItem {
  id: string;
  label: string;
  subtitle: string;
  icon: any;
  category: string;
  type: string;
}

interface Category {
  id: string;
  title: string;
  icon: any;
  items: ModuleItem[];
}

const categories: Category[] = [
  {
    id: 'interactive',
    title: 'Interactive Questions',
    icon: MessageSquare,
    items: [
      { id: 'multiple-choice', label: 'Multiple Choice', subtitle: 'Pick the right answer', icon: List, category: 'interactive', type: 'multiple-choice' },
      { id: 'word-cloud', label: 'Word Cloud', subtitle: 'Collaborative responses', icon: Cloud, category: 'interactive', type: 'word-cloud' },
      { id: 'open-ended', label: 'Open-ended', subtitle: 'Free text responses', icon: MessageSquare, category: 'interactive', type: 'open-ended' },
      { id: 'scales', label: 'Scales', subtitle: 'Rating responses', icon: BarChart3, category: 'interactive', type: 'scales' },
      { id: 'ranking', label: 'Ranking', subtitle: 'Order by preference', icon: Users, category: 'interactive', type: 'ranking' },
      { id: 'qa', label: 'Q&A', subtitle: 'Question & Answer', icon: HelpCircle, category: 'interactive', type: 'qa' },
      { id: 'pin-on-image', label: 'Pin on Image', subtitle: 'Interactive image points', icon: Target, category: 'interactive', type: 'pin-on-image' },
    ]
  },
  {
    id: 'quiz',
    title: 'Quiz Competitions',
    icon: Target,
    items: [
      { id: 'select-answer', label: 'Select Answer', subtitle: 'Quick quiz selection', icon: Target, category: 'quiz', type: 'select-answer' },
      { id: 'type-answer', label: 'Type Answer', subtitle: 'Written responses', icon: Type, category: 'quiz', type: 'type-answer' },
    ]
  },
  {
    id: 'content',
    title: 'Content Slides',
    icon: FileText,
    items: [
      { id: 'text', label: 'Text', subtitle: 'Rich text content', icon: FileText, category: 'content', type: 'text' },
      { id: 'image', label: 'Image', subtitle: 'Visual presentation', icon: Image, category: 'content', type: 'image' },
      { id: 'video', label: 'Video', subtitle: 'Media presentation', icon: Video, category: 'content', type: 'video' },
      { id: 'instructions', label: 'Instructions', subtitle: 'Step-by-step guide', icon: BookOpen, category: 'content', type: 'instructions' },
    ]
  },
  {
    id: 'integrations',
    title: 'Integrations',
    icon: ExternalLink,
    items: [
      { id: 'google-slides', label: 'Google Slides', subtitle: 'Import presentations', icon: ExternalLink, category: 'integrations', type: 'google-slides' },
      { id: 'powerpoint', label: 'PowerPoint', subtitle: 'Microsoft presentations', icon: Presentation, category: 'integrations', type: 'powerpoint' },
      { id: 'miro', label: 'Miro', subtitle: 'Collaborative boards', icon: Palette, category: 'integrations', type: 'miro' },
    ]
  }
];

// Mock recent items - in real app this would come from localStorage or backend
const recentItems: ModuleItem[] = [
  { id: 'multiple-choice', label: 'Multiple Choice', subtitle: 'Pick the right answer', icon: List, category: 'interactive', type: 'multiple-choice' },
  { id: 'text', label: 'Text', subtitle: 'Rich text content', icon: FileText, category: 'content', type: 'text' },
  { id: 'word-cloud', label: 'Word Cloud', subtitle: 'Collaborative responses', icon: Cloud, category: 'interactive', type: 'word-cloud' },
];

export function WorkflowSidebar() {
  const [selectedCategory, setSelectedCategory] = useState<string | null>(null);
  const [searchQuery, setSearchQuery] = useState('');

  const onDragStart = (event: React.DragEvent, item: ModuleItem) => {
    event.dataTransfer.setData('application/reactflow', item.type);
    event.dataTransfer.setData('application/nodedata', JSON.stringify({
      label: item.label,
      subtitle: item.subtitle,
      icon: item.icon.name,
      category: item.category
    }));
    event.dataTransfer.effectAllowed = 'move';
  };

  const filteredItems = (items: ModuleItem[]) => {
    if (!searchQuery) return items;
    return items.filter(item => 
      item.label.toLowerCase().includes(searchQuery.toLowerCase()) ||
      item.subtitle.toLowerCase().includes(searchQuery.toLowerCase())
    );
  };

  const renderModuleItem = (item: ModuleItem) => (
    <div
      key={item.id}
      draggable
      onDragStart={(e) => onDragStart(e, item)}
      className="flex items-center gap-3 p-3 rounded-lg border border-slate-200 bg-white hover:bg-slate-50 hover:border-slate-300 cursor-grab active:cursor-grabbing transition-all duration-200 hover:shadow-sm"
    >
      <div className="flex-shrink-0 p-2 rounded-md bg-slate-100">
        <item.icon className="w-4 h-4 text-slate-600" />
      </div>
      <div className="flex-1 min-w-0">
        <div className="text-sm font-medium text-slate-900">
          {item.label}
        </div>
        <div className="text-xs text-slate-500">
          {item.subtitle}
        </div>
      </div>
    </div>
  );

  // Main categories view
  if (!selectedCategory) {
    return (
      <div className="w-80 bg-white border-r border-slate-200 flex flex-col">
        {/* Header */}
        <div className="p-4 border-b border-slate-200">
          <div className="flex items-center gap-3 mb-3">
            <div className="p-2 rounded-lg bg-purple-100">
              <Brain className="w-5 h-5 text-purple-600" />
            </div>
            <h2 className="text-lg font-semibold text-slate-900">Smart Courseware</h2>
          </div>
          
          {/* Search Bar */}
          <div className="relative">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-slate-400" />
            <Input
              placeholder="Search templates"
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="pl-9 h-9 text-sm border-slate-200 focus:border-purple-300 focus:ring-purple-300"
            />
          </div>
        </div>

        {/* Categories Grid */}
        <div className="flex-1 p-4 space-y-3">
          {categories.map((category) => (
            <Button
              key={category.id}
              variant="ghost"
              onClick={() => setSelectedCategory(category.id)}
              className="w-full h-auto p-4 justify-start text-left hover:bg-slate-50 border border-slate-200 rounded-lg"
            >
              <div className="flex items-center gap-3">
                <div className="p-2 rounded-md bg-slate-100">
                  <category.icon className="w-5 h-5 text-slate-600" />
                </div>
                <div>
                  <div className="text-sm font-medium text-slate-900">
                    {category.title}
                  </div>
                  <div className="text-xs text-slate-500">
                    {category.items.length} templates
                  </div>
                </div>
              </div>
            </Button>
          ))}
        </div>
      </div>
    );
  }

  // Category detail view
  const category = categories.find(c => c.id === selectedCategory);
  if (!category) return null;

  return (
    <div className="w-80 bg-white border-r border-slate-200 flex flex-col">
      {/* Header with back button */}
      <div className="p-4 border-b border-slate-200">
        <div className="flex items-center gap-3 mb-3">
          <Button
            variant="ghost"
            size="sm"
            onClick={() => setSelectedCategory(null)}
            className="h-8 w-8 p-0"
          >
            <ChevronLeft className="h-4 w-4" />
          </Button>
          <div className="p-2 rounded-lg bg-purple-100">
            <category.icon className="w-5 h-5 text-purple-600" />
          </div>
          <h2 className="text-lg font-semibold text-slate-900">{category.title}</h2>
        </div>
        
        {/* Search Bar */}
        <div className="relative">
          <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-slate-400" />
          <Input
            placeholder={`Search ${category.title.toLowerCase()}`}
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="pl-9 h-9 text-sm border-slate-200 focus:border-purple-300 focus:ring-purple-300"
          />
        </div>
      </div>

      <div className="flex-1 overflow-y-auto">
        {/* Recently used section */}
        {recentItems.filter(item => item.category === selectedCategory).length > 0 && (
          <div className="p-4 border-b border-slate-100">
            <div className="flex items-center gap-2 mb-3">
              <Clock className="h-4 w-4 text-slate-500" />
              <h3 className="text-sm font-medium text-slate-700">Recently used</h3>
            </div>
            <div className="space-y-2">
              {recentItems
                .filter(item => item.category === selectedCategory)
                .slice(0, 3)
                .map(renderModuleItem)}
            </div>
          </div>
        )}

        {/* All templates */}
        <div className="p-4">
          <div className="flex items-center gap-2 mb-3">
            <Star className="h-4 w-4 text-slate-500" />
            <h3 className="text-sm font-medium text-slate-700">All templates</h3>
          </div>
          <div className="space-y-2">
            {filteredItems(category.items).map(renderModuleItem)}
          </div>
        </div>
      </div>
    </div>
  );
}